#include "hg_devicedataserver.h"
#include <QJsonDocument>
#include <QJsonObject>
#include "dpm_config.h"



HG_DeviceDataServer::HG_DeviceDataServer(QObject *parent) : QObject(parent)
{
    DPMClient * client =new DPMClient(this);
    user =new DPMUser(client);
    connect(user, SIGNAL(signalDatas(SocketDataPacket *    ,const QMap<QString,QVariant>&   )),
            this, SLOT(recDatas(SocketDataPacket *    ,const QMap<QString,QVariant>&   )));

    connect(user, SIGNAL(serverconnnet(bool )), this, SLOT(connnent(bool)));

    link();
}
void HG_DeviceDataServer::link(){
    DPM_Config * config = new DPM_Config();

    user->name=config->user;
    user->room=config->room;
    user->lobby=config->lobby;

    user->client->connet(config->getIP(),config->getPort());
}

void HG_DeviceDataServer::recDatas(SocketDataPacket * packet  ,const QMap<QString,QVariant>& par ){
    if(par.value(PACKET_EVENT_CODE).toInt()==EVENT_CODE_LOGIN){

        user->id=par.value(PACKET_SEND_UID).toString();
        user->name=par.value(PACKET_SEND_USER).toString();
        // emit message("登录成功 uid:"+ user->id +" user:"+user->name );
        return;

    }

    QString sendu =par.value(PACKET_SEND_USER).toString();

    QJsonParseError err_rpt;
    QJsonDocument  root_Doc = QJsonDocument::fromJson(packet->getDataByteArray(), &err_rpt);
    if(err_rpt.error != QJsonParseError::NoError)
    {
        qDebug() << "JSON格式错误";
        return ;
    }

    QJsonObject root_Obj = root_Doc.object();

    //数据名称
    QJsonValue datanValue = root_Obj.value("dataname");
    //数据均值
    QJsonValue averageValue = root_Obj.value("average");
    //所有数据
    QJsonValue datasValue =  root_Obj.value("datas");

    if(datanValue.toString()==unitWeight)
        emit signalDataParket(unitWeight,averageValue.toString(),datasValue.toString().split(";"));

    if(datanValue.toString()==waterContent)
         emit signalDataParket(waterContent,averageValue.toString(),datasValue.toString().split(";"));

}
void HG_DeviceDataServer::connnent(bool link){
    if(link)
        login();
}
///
/// \brief DPMClient::sendInfo
///发送用户信息
void HG_DeviceDataServer::login(){
    user->sendlogin();
}


///
/// \brief DPMClient::send
/// \param msg
///发出数据
void HG_DeviceDataServer::send(const QString& msg){

    user->sendMessageToRoom(msg);
}
